package com.base.common.util.file;

import com.base.common.util.BaseStringUtils;
import com.base.common.util.GeneratorUniqueID;
import com.base.common.util.pdf.AddQrcodeToPdfFileUtils;
import com.base.common.util.pdf.QrcodePdfInfo;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import sun.net.www.protocol.http.HttpURLConnection;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Calendar;

/**
 * @title 文件操作工具类
 * @Author 覃球球
 * @Version 1.0 on 2019/3/5.
 * @Copyright 贝旺科技
 */
public class BaseFileUtils {

    /**
     * @param baseDir 磁盘基准目录
     * @param type    类型  undergraduate(本科生)  postgraduate(研究生)
     * @return 返回生成的相对于 baseDir 的目录路径
     */
    public static String mkdirs(String baseDir, String type) {
        File parentDir = new File(baseDir, type);
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;

        String yearMonth = year + "/" + month;
        File subDir = new File(parentDir, yearMonth);
        if (!subDir.exists()) {
            subDir.mkdirs(); //创建目录
        }

        return type + "/" + yearMonth;
    }

    /**
     * 创建文件
     *
     * @param originUrl 源文件URL
     * @param baseDir   磁盘基准目录
     * @param type      类型  undergraduate(本科生)  postgraduate(研究生)
     * @return 返回生成的相对于 baseDir 的文件路径
     */
    public static String createFile(String originUrl, String baseDir, String type)
            throws Exception {
        if (StringUtils.isBlank(originUrl)) {
            throw new Exception("url不能为空 : " + originUrl);
        }

        String relativeDir = mkdirs(baseDir, type);
        String fileName = getFileName(originUrl);

        String destRelativeFileUrl = relativeDir + "/" + fileName;
        downlowadFile(originUrl, baseDir + "/" + destRelativeFileUrl);
        return destRelativeFileUrl;
    }

    private static String getFileName(String originUrl) {
        Calendar calendar = Calendar.getInstance();
        int date = calendar.get(Calendar.DAY_OF_MONTH);

        String extName = FilenameUtils.getExtension(originUrl);

        return (date < 10 ? "0" + date : date) + "_"
                + BaseStringUtils.getUuid() + "." + extName;
    }

    public static void main(String[] args)   {
        String baseDir = "e:/home";
        String destRelativeFileUrl = null;
        try{
            destRelativeFileUrl = createFile("http://127.0.0.1:8080/static/pdfjs/PDF/grade.pdf"
                    , baseDir, "postgraduate");
        }catch (IOException io){
            if(io instanceof java.net.SocketException){
                throw new RuntimeException("网络异常！");
            }
            throw new RuntimeException("网络异常, " + io.getMessage());
        }catch (Exception e){
            throw new RuntimeException("异常, " + e.getMessage());
        }

        QrcodePdfInfo pdfInfo = new QrcodePdfInfo();
        String originPdfUrl = baseDir + "/" + destRelativeFileUrl;
        pdfInfo.setOriginPdfFileUrl(originPdfUrl);
        pdfInfo.setCodeText(GeneratorUniqueID.createToken());
        pdfInfo.setHostUrl("https://ssl.beone2009.com/login");

        String  extName = FilenameUtils.getExtension(originPdfUrl);
        if(StringUtils.isNotBlank(extName)){
            originPdfUrl = originPdfUrl.substring(0, originPdfUrl.indexOf(extName) - 1);
            originPdfUrl = originPdfUrl + "_qr." + extName;
        }else {
            originPdfUrl = originPdfUrl + "_qr";
        }

        pdfInfo.setDestPdfFileUrl(originPdfUrl);
        String relativeQrcodePdfFile = originPdfUrl.replaceAll(baseDir + "/","");
        AddQrcodeToPdfFileUtils.addQrcodeToPdf(pdfInfo);

//        System.out.println(relativeQrcodePdfFile);
    }

    /**
     * 下载文件到指定位置
     *
     * @param originUrl
     * @param destFileUrl
     * @throws Exception
     */
    public static void downlowadFile(String originUrl, String destFileUrl) throws Exception {
        URL url = new URL(originUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        // 设置是否向HttpURLConnection输出
        connection.setDoOutput(false);
        // 设置是否从httpUrlConnection读入
        connection.setDoInput(true);
        // 设置请求方式
        connection.setRequestMethod("GET");
        // 设置是否使用缓存
        connection.setUseCaches(true);
        // 设置此 HttpURLConnection 实例是否应该自动执行 HTTP 重定向
        connection.setInstanceFollowRedirects(true);
        // 设置超时时间
        connection.setConnectTimeout(30000);
        // 连接
        connection.connect();
        // 4. 得到响应状态码的返回值 responseCode
        int code = connection.getResponseCode();
        InputStream in = null;
        FileOutputStream out = null;
        try {
            // 5. 如果返回值正常，数据在网络中是以流的形式得到服务端返回的数据
            if (code == 200) { // 正常
                in = connection.getInputStream();
                out = new FileOutputStream(destFileUrl);
                IOUtils.copy(in, out);
                return;
            }
            throw new Exception("网络异常, code = " + code);
        } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }
    }
}
